from fastapi import APIRouter, HTTPException
from typing import List, Dict, Any
from database.operations import (
    get_all_sessions,
    get_session_messages,
    delete_session,
    get_session
)

router = APIRouter(tags=["sessions"], prefix="/api")


@router.get("/sessions", response_model=List[Dict[str, Any]])
async def get_sessions():
    """获取所有会话"""
    try:
        return await get_all_sessions()
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取会话列表失败: {str(e)}")


@router.get("/sessions/{session_id}/messages", response_model=List[Dict[str, Any]])
async def get_messages(session_id: str):
    """获取特定会话的消息"""
    try:
        # 检查会话是否存在
        session = await get_session(session_id)
        if not session:
            raise HTTPException(status_code=404, detail="会话不存在")

        return await get_session_messages(session_id)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取会话消息失败: {str(e)}")


@router.delete("/sessions/{session_id}")
async def delete_session_endpoint(session_id: str):
    """删除会话及其中的消息"""
    try:
        result = await delete_session(session_id)
        if not result:
            raise HTTPException(status_code=404, detail="会话不存在")

        return {"status": "success", "message": "会话已删除"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除会话失败: {str(e)}")
